<template>
  <a-modal
    v-model:open="modalStatus"
    title="自动化配置"
    @ok="handleOk"
    @cancel="cancel"
    :width="850"
  >
    <a-form
      class="modal_form"
      :model="modalFrom"
      name="basic"
      :label-col="{ style: 'width: 120px' }"
    >
      <a-form-item label="自动化配置名称">
        <a-input
          v-model:value="modalFrom.configName"
          placeholder="请输入自动化配置名称"
          style="width: 280px"
        />
      </a-form-item>
      <a-form-item label="自动化配置">
        <div>
          <a-button
            class="add_live_config_btn"
            type="primary"
            @click="singleItemOpen"
          >
            添加配置
          </a-button>
        </div>
      </a-form-item>
      <a-table
        class="live_config_table"
        :columns="columns"
        :data-source="modalFrom.configTemplate"
        :pagination="false"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex == 'type'">
            {{ typeOptions.find((Item) => Item.value == record.type)?.label }}
          </template>
          <template v-if="column.dataIndex == 'interval'">
            {{ record.interval }}s
          </template>
          <template v-if="column.dataIndex == 'delay'">
            {{ record.delay }}s
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-dropdown :trigger="['click']">
              <template #overlay>
                <a-menu @click="handleMenuClick($event, record, index)">
                  <a-menu-item key="1"> 编辑 </a-menu-item>
                  <a-menu-item key="2"> 删除 </a-menu-item>
                </a-menu>
              </template>
              <a-button>
                操作
                <DownOutlined />
              </a-button>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </a-form>
  </a-modal>

  <singleItemPop
    ref="singleItemPopRef"
    @updateItem="updateItem"
  ></singleItemPop>
</template>

<script setup lang="ts">
import { Ref, ref } from "vue";
import singleItemPop from "./singleItemPop.vue";
import { ColumnsType } from "ant-design-vue/es/table";
import { typeOptions } from "./commit";
import { convertSecondToTime } from "./utils";
import { configType } from "./type";

const emit = defineEmits(["updateConfig"]);

const singleItemPopRef = ref();

const modalStatus = ref<boolean>(false);

const columns: ColumnsType = [
  {
    title: "配置类型",
    dataIndex: "type",
  },
  {
    title: "操作简述",
    dataIndex: "describe",
  },
  {
    title: "配置操作",
    dataIndex: "action",
  },
];

const modalFrom: Ref<configType> = ref({
  id: "",
  configName: "",
  configTemplate: [],
});

function handleOk() {
  emit("updateConfig", JSON.parse(JSON.stringify(modalFrom.value)));
  modalStatus.value = false;
  reset();
}

function updateItem(data: any) {
  let configData = JSON.parse(JSON.stringify(data));
  let index = data.index;
  delete data.index;
  if (index != -1) {
    modalFrom.value.configTemplate.splice(index, 1);
  } else {
    configData = data;
  }

  let describe = getDescribe(configData);
  configData.describe = describe;
  modalFrom.value.configTemplate.unshift(configData);
}

function deleteItem(index: number) {
  modalFrom.value.configTemplate.splice(index, 1);
}

function reset() {
  modalFrom.value.id = "";
  modalFrom.value.configName = "";
  modalFrom.value.configTemplate = [];
}

function singleItemOpen() {
  let showLuckyBag = false;
  let luckyIndex = modalFrom.value.configTemplate.findIndex(
    (item) => item.type == "luckyBag"
  );

  // 判断当前的单条配置是否应该有福袋选项
  if (location.href.includes("xiaohongshu")) {
    showLuckyBag = false;
  } else if (luckyIndex == -1) {
    showLuckyBag = true;
  }
  singleItemPopRef.value.open({ showLuckyBag });
}

function open(data?: any) {
  if (data) {
    modalFrom.value.id = data.id;
    modalFrom.value.configName = data.configName;
    modalFrom.value.configTemplate = data.configTemplate.map((item: any) => {
      let describe = getDescribe(item);
      return {
        ...item,
        describe,
      };
    });
  }
  modalStatus.value = true;
}

function getDescribe(config: any) {
  let delayObj = convertSecondToTime(config.delay);
  let intervalObj = convertSecondToTime(config.interval);
  let describe = "";
  if (config.type == "comment") {
    describe = `延迟${delayObj.text}, 每隔${intervalObj.text}`;
    if (config.commentText) {
      describe += `,发布“${config.commentText}”评论`;
    } else {
      describe += `,发布抖音第${config.serialNum || 1}条快捷评论`;
    }

    if (config.isTop) {
      describe += "并置顶";
    }
  } else if (config.type == "shoppIngpopUp") {
    describe = `延迟${delayObj.text}, 每隔${intervalObj.text}`;
    describe += `,弹出序号${config.serialNum || 1}的商品`;
  } else if (config.type == "luckyBag") {
    describe = `当人数小于等于${config.peopleNum}人后发布一次福袋`;
  }

  return describe;
}

function cancel() {
  modalStatus.value = false;
  reset();
}

function handleMenuClick(e: any, data: any, index: number) {
  if (e.key == 1) {
    let showLuckyBag = false;
    let luckyIndex = modalFrom.value.configTemplate.findIndex(
      (item) => item.type == "luckyBag"
    );

    // 判断当前的单条配置是否应该有福袋选项
    if (location.href.includes("xiaohongshu")) {
      showLuckyBag = false;
    } else if (data.type == "luckyBag") {
      showLuckyBag = true;
    } else if (luckyIndex == -1) {
      showLuckyBag = true;
    }
    singleItemPopRef.value.open({ ...data, showLuckyBag, index });
  } else if (e.key == 2) {
    deleteItem(index);
  }
}

defineExpose({
  open,
});
</script>

<style>
body .ant-modal-close-x {
  width: 20px;
  height: 20px;
}
</style>

<style scoped lang="less">
.modal_form {
  margin-top: 20px;
  .add_live_config_btn {
    display: block;
  }
}
</style>
